import json

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import ListAPIView ,CreateAPIView
from user import models,user_ser
from rest_framework.filters import OrderingFilter
# Create your views here.


from django.core.files.storage import default_storage
class Uploads(APIView):
    def post(self,request):
        file=request.data.get('file')
        types=['jpg','png']
        if file.name.split('.')[-1] not in types:
            return Response({'code':401,'msg':'文件类型不符合要求'})
        if file.size>1024*1024*3:
            return Response({'code':402,'msg':'文件过大要求'})
        uploadsfile=default_storage.save(f'img/{file.name}',file)
        url=default_storage.url(uploadsfile)
        return Response({'url':url})

from utils.jwttool import tool
import random
from utils.send import send_message
from utils.redis_tool import redistool
class Code(APIView):
    def get(self,request):
        phone=request.query_params.get('phone')
        code=random.randint(1000,9999)
        mycode=send_message(phone,code)
        resjson=json.loads(mycode)
        if resjson['statusCode']=='000000':
            redistool.setcode(phone,code)
            return Response({'code':200,'msg':'发送成功'})
        else:
            return Response({'code':400,'msg':'发送成功'})

class Login(APIView):
    def post(self,request):
        username=request.data.get('username')
        password=request.data.get('password')
        info=models.UserModel.objects.filter(username=username).first()
        if info:
            if info.password==password:
                token=tool.get_token(info.id)
                return Response({'code':200,'msg':'登录成功','data':{'token':token,'user_id':info.id}})

            else:
                return Response({'code':402,'msg':'密码错误'})

        else:
            return Response({'code':400,'msg':'用户名不存在'})

class LoginCode(APIView):
    def post(self,request):
        phone=request.data.get('phone')
        code=request.data.get('code')

        mycode=redistool.getcode(phone)
        if code!=mycode:
            return Response({'msg':'验证码错误','code':400})
        user=models.UserModel.objects.filter(phone=phone).first()
        if not user:
                user=models.UserModel.objects.create(phone=phone)





class Commit(ListAPIView):
    queryset = models.CommentModel.objects.all().order_by('-order')
    serializer_class = user_ser.CommentSer
    filter_backends = [OrderingFilter]
    ordering_fields=['id']

class Add(CreateAPIView):
    queryset = models.CommentModel.objects.all()
    serializer_class = user_ser.CommentSer


class Detail(APIView):
    def get(self,request):
        id=request.query_params.get('id')
        info=models.CommentModel.objects.filter(id=id).first()
        ser=user_ser.CommentSer(instance=info)
        return Response({'code':200,'data':ser.data})